package com.coai.message.model

import jakarta.persistence.*
import org.springframework.data.annotation.CreatedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.time.LocalDateTime

@Entity
@Table(
    name = "messages",
    indexes = [
        Index(name = "idx_conversation_id", columnList = "conversation_id"),
        Index(name = "idx_sender_id", columnList = "sender_id"),
        Index(name = "idx_created_at", columnList = "created_at")
    ]
)
@EntityListeners(AuditingEntityListener::class)
data class Message(
    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    val id: String? = null,
    
    @Column(name = "conversation_id", nullable = false)
    val conversationId: String,
    
    @Column(name = "sender_id", nullable = false)
    val senderId: String,
    
    @Enumerated(EnumType.STRING)
    @Column(name = "message_type", nullable = false, length = 20)
    val messageType: MessageType,
    
    @Column(nullable = false, columnDefinition = "TEXT")
    val content: String,
    
    @Column(columnDefinition = "TEXT")
    val metadata: String? = null, // JSON格式，存储额外信息
    
    @Column(name = "reply_to_id")
    val replyToId: String? = null, // 回复的消息ID
    
    @Column(nullable = false)
    var recalled: Boolean = false,
    
    @Column(name = "recalled_at")
    var recalledAt: LocalDateTime? = null,
    
    @CreatedDate
    @Column(nullable = false, updatable = false)
    val createdAt: LocalDateTime? = null,
    
    @Column(name = "deleted_at")
    var deletedAt: LocalDateTime? = null
)

enum class MessageType {
    TEXT,       // 文本消息
    IMAGE,      // 图片
    FILE,       // 文件
    VOICE,      // 语音
    VIDEO,      // 视频
    LOCATION,   // 位置
    SYSTEM,     // 系统消息
    CARD,       // 卡片消息
    AI_REPLY,   // AI回复
    AI_SUMMARY, // AI总结
    AI_TASK     // AI提取的任务
}

@Entity
@Table(
    name = "message_read_status",
    uniqueConstraints = [
        UniqueConstraint(columnNames = ["message_id", "user_id"])
    ]
)
data class MessageReadStatus(
    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    val id: String? = null,
    
    @Column(name = "message_id", nullable = false)
    val messageId: String,
    
    @Column(name = "user_id", nullable = false)
    val userId: String,
    
    @Column(name = "read_at", nullable = false)
    val readAt: LocalDateTime = LocalDateTime.now()
)
